<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/30 0030
 * Time: 上午 11:11
 */
namespace app\api\service;

use app\admin\model\Store;
use app\admin\model\Storesettlement;
use app\admin\model\Usersettlement;
use app\common\model\User;
use app\common\model\Userstore;
use app\lib\exception\OrderException;
use app\lib\exception\ParameterException;
use think\Db;
use think\Exception;
use think\Loader;
use think\Log;

Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');

class ShanghuPay{
    private $orderID;
    private $userId;

    function __construct($orderId,$userId)
    {
        $this->orderID = $orderId;
        $this->userId = $userId;
    }

    /**
     * 商户向用户打款
     * @return \think\response\Json
     */
    public function shanghuPay($type){
        if($type == 1){
            $comorder = Usersettlement::get($this->orderID);
        }else{
            $comorder = Storesettlement::get($this->orderID);
        }
        try{
            $this->checkComOrder($comorder,$type);
        }catch (Exception $ex){
            return show(2,$ex->msg,$ex->msg);
        }
        $res = $this->GoshanghuPay($comorder->amount,$comorder->orderNo,$type);
        if($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS'){
            return show(config('status.SUCCESS_STATUS'),'ok','支付成功');
        }else{
            if(!empty($res['err_code']) && $res['err_code'] == 'NOTENOUGH'){
                return show(config('status.ERROR_STATUS'),'支付失败','商户余额不足，请去微信商户平台充值');
            }elseif (!empty($res['err_code']) && $res['err_code'] == 'AMOUNT_LIMIT'){
                return show(config('status.ERROR_STATUS'),'支付失败','付款金额超限');
            }else{
                return show(config('status.ERROR_STATUS'),'支付失败','支付失败');
            }

        }

    }

    private function GoshanghuPay($amount,$OrderNo,$type){
        $openid = User::getopenId($this->userId);
        $wxOrderData = new \WxPayTransfers();
        $wxOrderData->SetPartner_trade_no($OrderNo);
        $wxOrderData->SetOpenid($openid);
        $wxOrderData->SetAmount($amount);
        $wxOrderData->SetDesc('收益提现');
        $wxOrderData->SetCheck_name('NO_CHECK');

        return $this->DoTransfers($wxOrderData,$type);
    }


    private function DoTransfers($wxOrderData,$type){

//        <xml>
//        <return_code><![CDATA[SUCCESS]]></return_code>
//        <return_msg><![CDATA[]]></return_msg>
//        <mch_appid><![CDATA[wxec38b8ff840bd989]]></mch_appid>
//        <mchid><![CDATA[10013274]]></mchid>
//        <device_info><![CDATA[]]></device_info>
//        <nonce_str><![CDATA[lxuDzMnRjpcXzxLx0q]]></nonce_str>
//        <result_code><![CDATA[SUCCESS]]></result_code>
//        <partner_trade_no><![CDATA[10013574201505191526582441]]></partner_trade_no>
//        <payment_no><![CDATA[1000018301201505190181489473]]></payment_no>
//        <payment_time><![CDATA[2015-05-19 15：26：59]]></payment_time>
//        </xml>

        $wxOrder = \WxPayApi::transfers($wxOrderData);
        if($wxOrder['return_code'] != 'SUCCESS' || $wxOrder['result_code'] != 'SUCCESS'){
            Log::record($wxOrder,'error');
            Log::record('商户向用户打款失败','error');
            if(isset($wxOrder['err_code']) && !empty($wxOrder['err_code'])){
                if($type == 1){
                    $usercom = Usersettlement::get($this->orderID);
                }else{
                    $usercom = Storesettlement::get($this->orderID);
                }
                $usercom->status = 2;
                $usercom->causefail = $wxOrder['err_code_des'];
                $usercom->save();
            }
        }else{
            //打款成功后处理逻辑
            $this->transfersSuccess($wxOrder,$type);
        }
        return $wxOrder;
    }


    private function transfersSuccess($wxOrder,$type){
        Db::startTrans();
        try
        {
            if($type == 1){
                $usercom = Usersettlement::where('orderNo',$wxOrder['partner_trade_no'])->find();
            }else{
                $usercom = Storesettlement::where('orderNo',$wxOrder['partner_trade_no'])->find();
            }

            $usercom->status = 1;
            $usercom->settleTime = $wxOrder['payment_time'];
            $usercom->tradeNo = $wxOrder['payment_no'];
            $usercom->save();
            Db::commit();

        }catch (Exception $ex){
            Db::rollback();
            Log::record($ex);
        }

    }

    //对用户佣金提现订单号进行检测
    private function checkComOrder($comorder,$type){
        if($type == 1){
            if($this->userId != $comorder->userId){
                throw new ParameterException([
                    'msg' => '提现用户不合法'
                ]);
            }
        }else{
            $User = \app\admin\model\User::get($this->userId);
            $Userstore = Userstore::where('userId',$User->id)->find();
            if($Userstore->storeId != $comorder->storeId){
                throw new ParameterException([
                    'msg' => '提现用户不合法'
                ]);
            }
        }
        if(!$comorder){
            throw new OrderException([
                'msg' => '提现订单号不存在'
            ]);
        }

        if($comorder->status != 0){
            throw new OrderException([
                'msg' => '该订单可能已经提现过了'
            ]);
        }
    }
}